//
//  MainTempModel.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2025/1/6.
//  Copyright © 2025 zwb. All rights reserved.
//
import UIKit
import ObjectMapper

public struct MainTempModel: Mappable {
    var query_url:String?
    var zones:String?
    var query_form_url:String?
    var delete_url:String?
    var unrefer_url:String?
    var refer_url:String?
    var save_url:String?
    var path = ""
    var MainParam = ""
    var detParam = ""
    
    var menu_nm:String?
    var directory_nm:String?
    var item_nm: String?
    var id_key: String?
    var res_id:String?
    var pic_url:String?
    var left_title:String?
    var right_title:String?
    var title_item: String?
    var audit_field:String?
    var is_operation_detail:String? // 0 否  1 是  2 仅新增可以编辑细表
    var upload_type:String?
    var is_auditFlow:String?
    var flow_voucd:String?
    var flow_flownm:String?
    var detail_num_max:String?
    var refer_ids:String?
    var refer_nms:String?// 引用菜单名称
    var referModels = [MainTempModel]()
    var details_nm:String?
    private  var detailsModes = [[String]]()
    var multiDetailsTitles = [String]()
    var multiDetailsParams = [String]()
    var multiDetailsOperates = [String]()
    var multiDetailsTitleKeys = [String]()
    
    
    var is_save_and_refer:String?
    var upload_file_type:String?// 图片位置标识
    var module_id:String? // 手动赋值手动赋值
    private var definition_btn:String?
    var defiBtnArr = [[String]]()
    private var grammar:String?
    var grmmarArr = [String]()
    var webFormUrl = ""
    
    var limitMakerModifyID = "" // 空就是不限制，有就是限制
    var listGroup = [String]()// 列表分组功能更   带两个字符串  左边 分组逻辑  右边  分组显示
    
    var setModifyForbidden = false // 禁止修改删除提交等操作，默认否
    var setViewForbidden = false // 禁止查看等操作，默认否

    var setAddForbidden = false // 禁止新增，默认否
    var setContinueAdd = false // 支持保存并新增 ， 默认否
    var continueParamsA:[String] = [] // 保存并新增的主表保留参数
    var continueParamsB:[String] = []// 保存并新增的细表保留参数
    var setFormButtonTitle = false   // 改变按钮名称, 只针对 submitButton 生效, 使用三目运算符
    
    var setCheckDevice = false // 绑定设备校验 ， 默认否
    var setGesturePwd = false // 手势密码保护 ， 默认否
    
    var scanOutsideParam = "" // 支持外部直接扫码, 字段指向 扫码字段参数
    var tempArr = [MainTempModel]()
    var is_use:String?  // 1 显示启用   2  隐藏启用（不常规显示，只给引用菜单，和按钮事件触发显示）   0 禁用（接口不返回）
    public init?(map: Map) {
        
    }
    // Mappable
    public mutating func mapping(map: Map) {
        tempArr <- map[TempSerialKeys.details]
        query_url <- map[TempSerialKeys.query_url]
        query_form_url <- map[TempSerialKeys.query_form_url]
        save_url <- map[TempSerialKeys.save_url]
        unrefer_url <- map[TempSerialKeys.unrefer_url]
        refer_url <- map[TempSerialKeys.refer_url]
        delete_url <- map[TempSerialKeys.delete_url]
        menu_nm <- map[TempSerialKeys.menu_nm]
        directory_nm <- map[TempSerialKeys.directory_nm]
        module_id <- (map[TempSerialKeys.module_id],StringTransform())
        
        refer_ids <- map[TempSerialKeys.refer_ids]
        refer_nms <- map[TempSerialKeys.refer_nms]
        is_use <- (map[TempSerialKeys.is_use],StringTransform())
        item_nm <- map[TempSerialKeys.item_nm]
        pic_url <- map[TempSerialKeys.pic_url]
        zones <- map[TempSerialKeys.zones]
        id_key <- (map[TempSerialKeys.id_key],StringTransform())
        res_id <- (map[TempSerialKeys.res_id],StringTransform())
        left_title <- map[TempSerialKeys.left_title]
        right_title <- map[TempSerialKeys.right_title]
        title_item <- map[TempSerialKeys.title_item]
        audit_field <- map[TempSerialKeys.audit_field]
        is_operation_detail <- (map[TempSerialKeys.is_operation_detail],StringTransform())
        detail_num_max <- (map[TempSerialKeys.detail_num_max],StringTransform())
        
        details_nm <- map[TempSerialKeys.details_nm]
        is_auditFlow <- (map[TempSerialKeys.is_audit],StringTransform())
        flow_voucd <- map[TempSerialKeys.flow_voucd]
        flow_flownm <- map[TempSerialKeys.flow_flownm]
        is_save_and_refer <- (map[TempSerialKeys.is_save_and_refer],StringTransform())
        upload_type <- map[TempSerialKeys.upload_type]
        upload_file_type <- map[TempSerialKeys.upload_file_type]
        definition_btn <- map[TempSerialKeys.definition_btn]
        grammar <- map[TempSerialKeys.grammar]
        
        
        // 处理主路径的path 和参数
        if save_url.unwrap.preChar(char: "?").unwrap.count == 0 {
//            print("❌ERROR: 配置菜单: \(menu_nm.unwrap) 的 save_url 错误, url 必须拼接参数!")
        }
        
        path = save_url.unwrap.preChar(char: "?").unwrap
        let arr = save_url.unwrap.sufChar(char: "?").unwrap.components(separatedBy: "&")
        
        
        for i in 0..<arr.count {
            let pre = arr[i].preChar(char: "=").unwrap
            var suf = arr[i].sufChar(char: "=").unwrap
            
            if i == 0 {
                MainParam = pre
            } else {
                detParam = pre
            }
        }
        
        
        
        
        let exp = grammar.unwrap
        grmmarArr = getParammerArr(exp)
        
        let mfArr = grmmarArr.filter{ $0.contains(GrammarType.setModifyForbidden.rawValue) }
        if mfArr.count > 0 {
            setModifyForbidden = true
        }
        let viewArr = grmmarArr.filter{ $0.contains(GrammarType.setViewForbidden.rawValue) }
        if viewArr.count > 0 {
            setViewForbidden = true
        }
        let aaArr = grmmarArr.filter{ $0.contains(GrammarType.setAddForbidden.rawValue) }
        if aaArr.count > 0 {
            setAddForbidden = true
        }
        let setArr = grmmarArr.filter { $0.contains(GrammarType.setFormButton.rawValue) }
        if setArr.count > 0 {
            setFormButtonTitle = true
        }
        
        // 保存并新增参数处理
        let saArr = grmmarArr.filter{ $0.contains(GrammarType.setContinueAdd.rawValue) }
        if saArr.count > 0 {
            setContinueAdd = true
            self.continueParamsA.removeAll()
            self.continueParamsB.removeAll()
            
            let caArr = saArr.first!.replacingOccurrences(of: GrammarType.setContinueAdd.rawValue, with: "").removeBrackets.removeDolendAt.components(separatedBy: ",")
            for item in caArr {
                if item.contains("b.") {
                    let rv = item.replacingOccurrences(of: "b.", with: "")
                    self.continueParamsB.append(rv)
                } else {
                    let rv = item.replacingOccurrences(of: "a.", with: "")
                    self.continueParamsA.append(rv)
                }
            }
            
            
        }
        
        // 列表分组参数整理
        let saveVArr = grmmarArr.filter{ $0.contains(GrammarType.setListGroup.rawValue) }
        // 表达式逻辑校验
        for xxx in saveVArr {
            let arrrr = getKeyPara(xxx)
            guard arrrr.count > 0 else {
                return
            }
            if arrrr.first! == GrammarType.setListGroup.rawValue {
                var brrrr = arrrr
                brrrr.remove(at: 0)
                guard brrrr.count == 1 else {
                    return
                }
                listGroup = brrrr.first!.components(separatedBy: ":")
                
            }
        }
        
        let ccArr = grmmarArr.filter{ $0.contains(GrammarType.setCheckDevice.rawValue) }
        if ccArr.count > 0 {
            setCheckDevice = true
        }
        let ggArr = grmmarArr.filter{ $0.contains(GrammarType.setGesturePwd.rawValue) }
        if ggArr.count > 0 {
            setGesturePwd = true
        }
        
        let limitMakerM = grmmarArr.filter{ $0.contains(GrammarType.setLimitMakerModify.rawValue) }
        if limitMakerM.count > 0 {
            self.limitMakerModifyID = limitMakerM.first!.replacingOccurrences(of: GrammarType.setLimitMakerModify.rawValue, with: "").removeBrackets.removeDolendAt
        }
        let setWebForm = grmmarArr.filter{ $0.contains(GrammarType.setWebForm.rawValue) }
        
        if setWebForm.count > 0 {
            var dd = setWebForm.first!.replacingOccurrences(of: "setWebForm@{", with: "")
            dd.removeLast()
            self.webFormUrl = dd
            
            
            KSLog("webFormUrl")
            KSLog(self.webFormUrl)
        }
        
        let sfArr = grmmarArr.filter{ $0.contains(GrammarType.setScanOutside.rawValue) }
        if sfArr.count > 0 {
            self.scanOutsideParam = sfArr.first!.replacingOccurrences(of: GrammarType.setScanOutside.rawValue, with: "").removeBrackets.removeDolendAt
        }
        
        let dNm =  details_nm.unwrap.components(separatedBy: ";").filter{$0 != ""}
        detailsModes = dNm.compactMap { one -> [String] in
            let ss = one.components(separatedBy: ":")
            return ss
        }
        multiDetailsTitleKeys = detailsModes.compactMap { one in
            if one.count > 1 {
                return one[1]
            }
            return ""
        }
        multiDetailsTitles.removeAll()
        multiDetailsParams.removeAll()
        multiDetailsOperates.removeAll()
        for i in 0..<detailsModes.count {
            let onex = detailsModes[i]
            if onex.count > 2 {
                multiDetailsTitles.append(onex[0])
                multiDetailsParams.append(onex[1])
                multiDetailsOperates.append(onex[2])
            } else {
                alertUtil(title: "提醒:\(menu_nm.unwrap)",message: "请确认\n细表名称格式：细表中文:细表字段名:细表是否可编辑\n只有多细表需要填写，一条细表无需填写  “细表名称”  内容",withCancel: false, operateS: [nameAction(name: "确认", action: { _ in
                    
                })])
                
            }
        }
        
    
        // null 就默认可操作细表
        for i in 0..<multiDetailsOperates.count {
            if multiDetailsOperates[i] == "null" {
                multiDetailsOperates[i] = "1"
            }
        }
        
        
        let dfiNm =  definition_btn.unwrap.components(separatedBy: ";").filter{$0 != ""}
        defiBtnArr = dfiNm.compactMap { one -> [String] in
            let oneA = one.components(separatedBy: ":")
            let resultOne = oneA.compactMap{$0.replacingOccurrences(of: "#", with: ":")}
            return resultOne
        }
        
        
    }
    public func dictionaryRepresentation() -> [String: Any] {
        var dictionary: [String: Any] = [:]
        if let value = details_nm { dictionary[TempSerialKeys.details_nm] = value }
        if let value = grammar { dictionary[TempSerialKeys.grammar] = value }
        if let value = zones { dictionary[TempSerialKeys.zones] = value }
        
        return dictionary
    }
}
